﻿namespace CleverCMS.Cms.Services.Infrastructure
{
    using MvcSiteMapProvider;
    using System;
    using System.Linq;
    using System.Collections.Generic;

    using Core.Infrastructure;

    public class RolesDynamicNodeProvider : DynamicNodeProviderBase
    {
        private AccountService      m_accountService;
        private readonly AppCache   m_appCache;

        public RolesDynamicNodeProvider()
        {
            this.m_appCache = new AppCache();
        }

        public override IEnumerable<DynamicNode> GetDynamicNodeCollection(ISiteMapNode node)
        {
            if (m_appCache.Exists("Roles"))
                return (List<DynamicNode>)m_appCache.Get("Roles");


            //TODO: Why this can not be instanciated via IoC on obect creation? Rework sameway as its done for controllers (custom factory in the pipeline)?
            m_accountService = IoC.Get<AccountService>();
            var nodes = new List<DynamicNode>();

            var roles = m_accountService.LoadAllRoles();
            foreach (var role in roles)
            {
                var roleNode = new DynamicNode
                {
                    Key = "role_" + Guid.NewGuid() + "_" + role.RoleId,
                    Title = role.RoleName
                };
                roleNode.RouteValues.Add("id", role.RoleId);
                roleNode.Action = "Edit";
                roleNode.Controller = "Role";
                roleNode.Area = "CleverCms.Admin";
                nodes.Add(roleNode);
            }

            m_appCache.Add("Roles", nodes);
            return nodes;
        }
    }

}
